<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops" xmlns:m="http://www.w3.org/1998/Math/MathML" xmlns:pls="http://www.w3.org/2005/01/pronunciation-lexicon" xmlns:ssml="http://www.w3.org/2001/10/synthesis" xmlns:svg="http://www.w3.org/2000/svg">
  <head>
    <title>Exception handling</title>
    <link rel="stylesheet" type="text/css" href="docbook-epub.css"/>
    <link rel="stylesheet" type="text/css" href="kawa.css"/>
    <script src="kawa-ebook.js" type="text/javascript"/>
    <meta name="generator" content="DocBook XSL-NS Stylesheets V1.79.1"/>
    <link rel="prev" href="Threads.xhtml" title="Threads"/>
    <link rel="next" href="Control-features.xhtml" title="Control features"/>
  </head>
  <body>
    <header/>
    <section class="sect1" title="Exception handling" epub:type="subchapter" id="Exceptions">
      <div class="titlepage">
        <div>
          <div>
            <h2 class="title" style="clear: both">Exception handling</h2>
          </div>
        </div>
      </div>
      <p>An <em class="firstterm">exception</em> is an object used to signal an error or
other exceptional situation.  The program or run-time system
can <em class="firstterm">throw</em> the exception when an error is discovered.
An exception handler is a program construct that registers
an action to handle exceptions when the handler is active.
</p>
      <p>If an exception is thrown and not handled then the
read-eval-print-loop will print a stack trace, and bring
you back to the top level prompt.
When not running interactively, an unhandled exception
will normally cause Kawa to be exited.
</p>
      <p>In the Scheme exception model (as of R6RS and R7RS),
exception handlers are one-argument procedures that determine
the action the program takes when an exceptional situation is signaled.
The system implicitly maintains a
current exception handler in the dynamic environment.
The program raises an exception by invoking the current
exception handler, passing it an object encapsulating information
about the exception. Any procedure accepting
one argument can serve as an exception handler and any
object can be used to represent an exception.
</p>
      <p>The Scheme exception model is implemented on top of the Java VM’s
native exception model where the only objects that
can be thrown are instances of <code class="literal">java.lang.Throwable</code>.
Kawa also provides direct access to this native model,
as well as older Scheme exception models.
</p>
      <p class="synopsis" kind="Procedure"><span class="kind">Procedure</span><span class="ignore">: </span><a id="idm139667877955472" class="indexterm"/> <code class="function">with-exception-handler</code> <em class="replaceable"><code>handler</code></em> <em class="replaceable"><code>thunk</code></em></p>
      <div class="blockquote">
        <blockquote class="blockquote">
          <p>It is an error if <em class="replaceable"><code>handler</code></em> does not accept one argument.
It is also an error if <em class="replaceable"><code>thunk</code></em> does not accept zero arguments.
The <code class="literal">with-exception-handler</code> procedure returns the results
of invoking <em class="replaceable"><code>thunk</code></em>. The <em class="replaceable"><code>handler</code></em> is installed as the current
exception handler in the dynamic environment used for the
invocation of <em class="replaceable"><code>thunk</code></em>.
</p>
          <pre class="screen">(call-with-current-continuation
  (lambda (k)
   (with-exception-handler
    (lambda (x)
     (display "condition: ")
     (write x)
     (newline)
     (k 'exception))
    (lambda ()
     (+ 1 (raise ’an-error))))))
       ⇒ exception
       <span class="emphasis"><em>and prints</em></span> condition: an-error
</pre>
          <pre class="screen">(with-exception-handler
 (lambda (x)
  (display "something went wrong\n"))
 (lambda ()
  (+ 1 (raise ’an-error))))
    <span class="emphasis"><em>prints</em></span> something went wrong
</pre>
          <p>After printing, the second example then raises another exception.
</p>
          <p><span class="emphasis"><em>Performance note:</em></span> The <em class="replaceable"><code>thunk</code></em> is inlined if it is a
lambda expression.  However, the <em class="replaceable"><code>handler</code></em> cannot be inlined
even if it is a lambda expression, because it could be called by
<code class="literal">raise-continuable</code>.  Using the <code class="literal">guard</code> form is
usually more efficient.
</p>
        </blockquote>
      </div>
      <p class="synopsis" kind="Procedure"><span class="kind">Procedure</span><span class="ignore">: </span><a id="idm139667877943360" class="indexterm"/> <code class="function">raise</code> <em class="replaceable"><code>obj</code></em></p>
      <div class="blockquote">
        <blockquote class="blockquote">
          <p>Raises an exception by invoking the current exception handler on <em class="replaceable"><code>obj</code></em>.
The handler is called with the same dynamic
environment as that of the call to raise, except that the
current exception handler is the one that was in place when
the handler being called was installed. If the handler returns,
then <em class="replaceable"><code>obj</code></em> is re-raised in the same dynamic environment as the handler.
</p>
          <p>If <em class="replaceable"><code>obj</code></em> is an instance of <code class="literal">java.lang.Throwable</code>,
then <code class="literal">raise</code> has the same effect as <code class="literal">primitive-throw</code>.
</p>
        </blockquote>
      </div>
      <p class="synopsis" kind="Procedure"><span class="kind">Procedure</span><span class="ignore">: </span><a id="idm139667877936736" class="indexterm"/> <code class="function">raise-continuable</code> <em class="replaceable"><code>obj</code></em></p>
      <div class="blockquote">
        <blockquote class="blockquote">
          <p>Raises an exception by invoking the current exception handler on <em class="replaceable"><code>obj</code></em>.
The handler is called with the same dynamic
environment as the call to <code class="literal">raise-continuable</code>, except
that: (1) the current exception handler is the one that was
in place when the handler being called was installed, and
(2) if the handler being called returns, then it will again
become the current exception handler.
If the handler returns, the values it returns become the values
returned by the call to <code class="literal">raise-continuable</code>.
</p>
          <pre class="screen">(with-exception-handler
  (lambda (con)
    (cond
      ((string? con)
       (display con))
      (else
       (display "a warning has been issued")))
    42)
  (lambda ()
    (+ (raise-continuable "should be a number")
       23)))
      <span class="emphasis"><em>prints:</em></span> should be a number
      ⇒ 65
</pre>
        </blockquote>
      </div>
      <p class="synopsis" kind="Syntax"><span class="kind">Syntax</span><span class="ignore">: </span><a id="idm139667877930560" class="indexterm"/> <code class="function">guard</code> <em class="replaceable"><code><em class="replaceable"><code>variable</code></em></code></em> <em class="replaceable"><code><a class="link" href="Conditionals.xhtml#meta-cond-clause"><em class="replaceable"><code>cond-clause</code></em></a></code></em><em class="replaceable"><code><sup>+</sup></code></em> <em class="replaceable"><code><a class="link" href="Bodies.xhtml#meta-body"><em class="replaceable"><code>body</code></em></a></code></em></p>
      <div class="blockquote">
        <blockquote class="blockquote">
          <p>The <em class="replaceable"><code>body</code></em> is evaluated with an exception handler that binds
the raised object to <em class="replaceable"><code>variable</code></em> and, within the scope of that binding,
evaluates the clauses as if they were the clauses of a <code class="literal">cond</code> expression.
That implicit <code class="literal">cond</code> expression is evaluated with
the continuation and dynamic environment of the <code class="literal">guard</code>
expression. If every cond-clause’s test evaluates to <code class="literal">#f</code>
and there is no <code class="literal">else</code> clause, then <code class="literal">raise-continuable</code> is
invoked on the raised object within the dynamic environment of the
original call to <code class="literal">raise</code> or <code class="literal">raise-continuable</code>,
except that the current exception handler is that of the
<code class="literal">guard</code> expression.
</p>
          <pre class="screen">(guard (condition
         ((assq 'a condition) =&gt; cdr)
         ((assq 'b condition)))
  (raise (list (cons 'a 42))))
      ⇒ 42
</pre>
          <pre class="screen">(guard (condition
         ((assq 'a condition) =&gt; cdr)
         ((assq 'b condition)))
  (raise (list (cons 'b 23))))
      ⇒ (b . 23)
</pre>
          <p><span class="emphasis"><em>Performance note:</em></span> Using <code class="literal">guard</code> is moderately efficient:
there is some overhead compared to using native exception handling,
but both the <em class="replaceable"><code>body</code></em> and the handlers in the <em class="replaceable"><code>cond-clause</code></em>
are inlined.
</p>
        </blockquote>
      </div>
      <p class="synopsis" kind="Procedure"><span class="kind">Procedure</span><span class="ignore">: </span><a id="idm139667877915776" class="indexterm"/> <code class="function">dynamic-wind</code> <em class="replaceable"><code>in-guard</code></em> <em class="replaceable"><code>thunk</code></em> <em class="replaceable"><code>out-guard</code></em></p>
      <div class="blockquote">
        <blockquote class="blockquote">
          <p>All three arguments must be 0-argument procedures.
First calls <em class="replaceable"><code>in-guard</code></em>, then <em class="replaceable"><code>thunk</code></em>, then <em class="replaceable"><code>out-guard</code></em>.
The result of the expression is that of <em class="replaceable"><code>thunk</code></em>.
If <em class="replaceable"><code>thunk</code></em> is exited abnormally (by throwing an exception or
invoking a continuation), <em class="replaceable"><code>out-guard</code></em> is called.
</p>
          <p>If the continuation of the dynamic-wind is re-entered (which
is not yet possible in Kawa), the <em class="replaceable"><code>in-guard</code></em> is called again.
</p>
          <p>This function was added in R5RS.
</p>
        </blockquote>
      </div>
      <p class="synopsis" kind="Procedure"><span class="kind">Procedure</span><span class="ignore">: </span><a id="idm139667877907360" class="indexterm"/> <code class="function">read-error?</code> <em class="replaceable"><code>obj</code></em></p>
      <div class="blockquote">
        <blockquote class="blockquote">
          <p>Returns #t if <em class="replaceable"><code>obj</code></em> is an object raised by the <code class="literal">read</code> procedure.
(That is if <em class="replaceable"><code>obj</code></em> is a <code class="literal">gnu.text.SyntaxException</code>.)
</p>
        </blockquote>
      </div>
      <p class="synopsis" kind="Procedure"><span class="kind">Procedure</span><span class="ignore">: </span><a id="idm139667877902272" class="indexterm"/> <code class="function">file-error?</code> <em class="replaceable"><code>obj</code></em></p>
      <div class="blockquote">
        <blockquote class="blockquote">
          <p>Returns #t if <em class="replaceable"><code>obj</code></em> is an object raised by inability to open an input
or output port on a file.
(This includes <code class="literal">java.io.FileNotFoundException</code> as well
as certain other exceptions.)
</p>
        </blockquote>
      </div>
      <section class="sect2" title="Simple error objects" epub:type="division" id="idm139667877898080">
        <div class="titlepage">
          <div>
            <div>
              <h3 class="title">Simple error objects</h3>
            </div>
          </div>
        </div>
        <p class="synopsis" kind="Procedure"><span class="kind">Procedure</span><span class="ignore">: </span><a id="idm139667877897008" class="indexterm"/> <code class="function">error</code> <em class="replaceable"><code>message</code></em> <em class="replaceable"><code>obj</code></em> <em class="replaceable"><code>...</code></em></p>
        <div class="blockquote">
          <blockquote class="blockquote">
            <p>Raises an exception as if by calling <code class="literal">raise</code>
on a newly allocated <em class="firstterm">simple error object</em>,
which encapsulates the information provided by <em class="replaceable"><code>message</code></em>
(which should a string), as well as any <em class="replaceable"><code>obj</code></em> arguments,
known as the irritants.
</p>
            <p>The string representation of a simple error object is as if calling
<code class="literal">(format "#&lt;ERROR ~a~{ ~w~}&gt;" <em class="replaceable"><code>message</code></em> <em class="replaceable"><code>irritants</code></em>)</code>.
(That is the <em class="replaceable"><code>message</code></em> is formatted as if with <code class="literal">display</code>
while each irritant <em class="replaceable"><code>obj</code></em> is formatted as if with <code class="literal">write</code>.)
</p>
            <p>This procedure is part of SRFI-23, and R7RS.
It differs from (and is incompatible with) R6RS’s <code class="literal">error</code> procedure.
</p>
          </blockquote>
        </div>
        <p class="synopsis" kind="Procedure"><span class="kind">Procedure</span><span class="ignore">: </span><a id="idm139667877886416" class="indexterm"/> <code class="function">error-object?</code> <em class="replaceable"><code>obj</code></em></p>
        <div class="blockquote">
          <blockquote class="blockquote">
            <p>Returns <code class="literal">#t</code> if <em class="replaceable"><code>obj</code></em> is a simple error object.
Specifically, that <em class="replaceable"><code>obj</code></em> is an instance of <code class="literal">kawa.lang.NamedException</code>.
Otherwise, it returns <code class="literal">#f</code>.
</p>
          </blockquote>
        </div>
        <p class="synopsis" kind="Procedure"><span class="kind">Procedure</span><span class="ignore">: </span><a id="idm139667877880928" class="indexterm"/> <code class="function">error-object-message</code> <em class="replaceable"><code>error-object</code></em></p>
        <div class="blockquote">
          <blockquote class="blockquote">
            <p>Returns the message encapsulated by error-object,
which must be a simple error object.
</p>
          </blockquote>
        </div>
        <p class="synopsis" kind="Procedure"><span class="kind">Procedure</span><span class="ignore">: </span><a id="idm139667877877488" class="indexterm"/> <code class="function">error-object-irritants</code> <em class="replaceable"><code>error-object</code></em></p>
        <div class="blockquote">
          <blockquote class="blockquote">
            <p>Returns a list of the irritants (other arguments)
encapsulated by error-object, which must be a simple error object.
</p>
          </blockquote>
        </div>
      </section>
      <section class="sect2" title="Named exceptions" epub:type="division" id="idm139667877874016">
        <div class="titlepage">
          <div>
            <div>
              <h3 class="title">Named exceptions</h3>
            </div>
          </div>
        </div>
        <p>These functions associate a symbol with exceptions
and handlers: A handler catches an exception if the symbol matches.
</p>
        <p class="synopsis" kind="Procedure"><span class="kind">Procedure</span><span class="ignore">: </span><a id="idm139667877872432" class="indexterm"/> <code class="function">catch</code> <em class="replaceable"><code>key</code></em> <em class="replaceable"><code>thunk</code></em> <em class="replaceable"><code>handler</code></em></p>
        <div class="blockquote">
          <blockquote class="blockquote">
            <p>Invoke <em class="replaceable"><code>thunk</code></em> in the dynamic context of <em class="replaceable"><code>handler</code></em> for
exceptions matching <em class="replaceable"><code>key</code></em>.  If thunk throws to the symbol <em class="replaceable"><code>key</code></em>,
then <em class="replaceable"><code>handler</code></em> is invoked this way:
</p>
            <pre class="screen">(handler key args ...)
</pre>
            <p><em class="replaceable"><code>key</code></em> may be a symbol.  The <em class="replaceable"><code>thunk</code></em> takes no
arguments.  If <em class="replaceable"><code>thunk</code></em> returns normally, that is the return value of
<code class="literal">catch</code>.
</p>
            <p>Handler is invoked outside the scope of its own <code class="literal">catch</code>.  If
<em class="replaceable"><code>handler</code></em> again throws to the same key, a new handler from further
up the call chain is invoked.
</p>
            <p>If the key is <code class="literal">#t</code>, then a throw to <span class="emphasis"><em>any</em></span> symbol will match
this call to <code class="literal">catch</code>.
</p>
          </blockquote>
        </div>
        <p class="synopsis" kind="Procedure"><span class="kind">Procedure</span><span class="ignore">: </span><a id="idm139667877860480" class="indexterm"/> <code class="function">throw</code> <em class="replaceable"><code>key</code></em> <em class="replaceable"><code>arg</code></em> <em class="replaceable"><code>...</code></em></p>
        <div class="blockquote">
          <blockquote class="blockquote">
            <p>Invoke the catch form matching <em class="replaceable"><code>key</code></em>, passing the <em class="replaceable"><code>arg</code></em>s to the
current <em class="replaceable"><code>handler</code></em>.  
</p>
            <p>If the key is a symbol it will match catches of the same
symbol or of <code class="literal">#t</code>.
</p>
            <p>If there is no handler at all, an error is signaled.
</p>
          </blockquote>
        </div>
      </section>
      <section class="sect2" title="Native exception handling" epub:type="division" id="idm139667877853776">
        <div class="titlepage">
          <div>
            <div>
              <h3 class="title">Native exception handling</h3>
            </div>
          </div>
        </div>
        <p class="synopsis" kind="Procedure"><span class="kind">Procedure</span><span class="ignore">: </span><a id="idm139667877852688" class="indexterm"/> <code class="function">primitive-throw</code> <em class="replaceable"><code>exception</code></em></p>
        <div class="blockquote">
          <blockquote class="blockquote">
            <p>Throws the <em class="replaceable"><code>exception</code></em>, which must be an instance of a sub-class
of <code class="literal">java.lang.Throwable</code>.
</p>
          </blockquote>
        </div>
        <p class="synopsis" kind="Syntax"><span class="kind">Syntax</span><span class="ignore">: </span><a id="idm139667877848416" class="indexterm"/> <code class="function">try-finally</code> <em class="replaceable"><code>body</code></em> <em class="replaceable"><code>handler</code></em></p>
        <div class="blockquote">
          <blockquote class="blockquote">
            <p>Evaluate <em class="replaceable"><code>body</code></em>, and return its result.
However, before it returns, evaluate <em class="replaceable"><code>handler</code></em>.
Even if <em class="replaceable"><code>body</code></em> returns abnormally (by throwing an exception),
<em class="replaceable"><code>handler</code></em> is evaluated.
</p>
            <p>(This is implemented just like Java’s <code class="literal">try</code>-<code class="literal">finally</code>.
However, the current implementation does not duplicate the <em class="replaceable"><code>handler</code></em>.)
</p>
          </blockquote>
        </div>
        <p class="synopsis" kind="Syntax"><span class="kind">Syntax</span><span class="ignore">: </span><a id="idm139667877840976" class="indexterm"/> <code class="function">try-catch</code> <em class="replaceable"><code>body</code></em> <em class="replaceable"><code>handler</code></em> <em class="replaceable"><code>...</code></em></p>
        <div class="blockquote">
          <blockquote class="blockquote">
            <p>Evaluate <em class="replaceable"><code>body</code></em>, in the context of the given <em class="replaceable"><code>handler</code></em> specifications.
Each <em class="replaceable"><code>handler</code></em> has the form:
</p>
            <pre class="screen"><em class="replaceable"><code>var</code></em> <em class="replaceable"><code>type</code></em> <em class="replaceable"><code>exp</code></em> ...
</pre>
            <p>If an exception is thrown in <em class="replaceable"><code>body</code></em>, the first <em class="replaceable"><code>handler</code></em>
is selected such that the thrown exception is an instance of
the <em class="replaceable"><code>handler</code></em>’s <em class="replaceable"><code>type</code></em>. If no <em class="replaceable"><code>handler</code></em> is selected,
the exception is propagated through the dynamic execution context
until a matching <em class="replaceable"><code>handler</code></em> is found.  (If no matching <em class="replaceable"><code>handler</code></em>
is found, then an error message is printed, and the computation terminated.)
</p>
            <p>Once a <em class="replaceable"><code>handler</code></em> is selected,
the <em class="replaceable"><code>var</code></em> is bound to the thrown exception, and the <em class="replaceable"><code>exp</code></em> in
the <em class="replaceable"><code>handler</code></em> are executed.  The result of the <code class="literal">try-catch</code>
is the result of <em class="replaceable"><code>body</code></em> if no exception is thrown, or the
value of the last <em class="replaceable"><code>exp</code></em> in the selected <em class="replaceable"><code>handler</code></em> if an
exception is thrown.
</p>
            <p>(This is implemented just like Java’s <code class="literal">try</code>-<code class="literal">catch</code>.)
</p>
          </blockquote>
        </div>
      </section>
    </section>
    <footer>
      <div class="navfooter">
        <ul>
          <li>
            <b class="toc">
              <a href="Exceptions.xhtml#idm139667877898080">Simple error objects</a>
            </b>
          </li>
          <li>
            <b class="toc">
              <a href="Exceptions.xhtml#idm139667877874016">Named exceptions</a>
            </b>
          </li>
          <li>
            <b class="toc">
              <a href="Exceptions.xhtml#idm139667877853776">Native exception handling</a>
            </b>
          </li>
        </ul>
        <p>
          Up: <a accesskey="u" href="Program-structure.xhtml">Program structure</a></p>
        <p>
        Previous: <a accesskey="p" href="Threads.xhtml">Threads</a></p>
      </div>
    </footer>
  </body>
</html>
